/*
 * @Author: zxh
 * @Email: 1271027008@qq.com
 * @Date: 2020-02-24 08:53:29
 * @Descripttion: 多发/多收
 */
import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { ManysendreciveListService } from './manysendrecive-list.service'
import { NzModalService } from 'ng-zorro-antd/modal';
import { HCommonService } from 'src/app/h-common/h-common.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-manysendrecive-list',
  templateUrl: './manysendrecive-list.component.html',
  styleUrls: ['./manysendrecive-list.component.scss']
})
export class ManysendreciveListComponent implements OnInit {

  power:any//权限
  modalDomBox : any

  constructor(
    private ManysendreciveListService: ManysendreciveListService,
    private datePipe: DatePipe,
    private nzModal:NzModalService,
    private HCommonService:HCommonService,
    private message:NzMessageService
  ) { }

  ngOnInit() {
    this.modalDomBox = document.querySelector("#modal_box");
    /* 获取权限 */
    this.power = this.HCommonService.getRoles("adjustAmount");

    this.getKFList()
    this.getMaterialList()
    this.getRecordList()
    this.getInOutList()
    this.getAccount()
    this.getGZLList()
  }

  kfList = [];
  kqList = [];
  wlList = [];
  // 获取库房 库区
  getKFList() {
    this.ManysendreciveListService.getAllKF().subscribe(res => {
      this.kfList = res
    })
  }
  // 选择库房
  selectedkf(kfId) {
    this.kfId = kfId
    this.kfList.forEach(item => {
      if (item.id == kfId) {
        this.kqList = item.warehouseAreas
      }
    })
    this.getRecordList('search')
  }
  // 选择库区
  selectedkq(kqId) {
    this.kqId = kqId
    if (this.kfId == '' && this.kqId == '') {
      this.kfId = ''
      this.kqId = ''
    }
    this.getMaterialList()
    this.getRecordList('search')
  }
  // 获取物料
  getMaterialList(modal?) {
    let _newKFId = '', _newKQId = ''
    if (modal) {
      _newKFId = this.kfIdModal
      _newKQId = this.kqIdModal
    } else {
      _newKFId = this.kfId
      _newKQId = this.kqId
    }
    if (_newKFId != '' && _newKQId != '') {
      let _dataJson = {
        warehouseId: _newKFId,
        warehouseAreaId: _newKQId
      }
      this.ManysendreciveListService.getMaterialCode(_dataJson).subscribe(res => {
        this.wlList = res
      })
    } else {
      this.ManysendreciveListService.getAllWl().subscribe(res => {
        let _newList = []
        res.forEach(item => {
          _newList.push({
            id: item.id,
            materialCode: item.code,
            materialName: item.name
          })
        });
        this.wlList = _newList
      })
    }
  }
  // 选择物料
  selectedwl(wlCode) {
    this.materialCode = wlCode
    this.wlList.forEach(item => {
      if (item.materialCode == wlCode) {
        this.materialName = item.materialName
      }
    })
    if (wlCode == '') {
      this.materialName = ''
    }
    this.getRecordList('search')
  }
  // 日期选择
  onDateChange(result: Date): void {
    let startTime = this.formatDate(result[0])
    let endTime = this.formatDate(result[1])
    this.dateRange = [startTime + " 00:00:00", endTime + " 23:59:59"]
    if(!startTime){
      this.dateRange = []
    }
    this.getRecordList('search')
  }
  // 时间格式化
  formatDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
  kfId: string = '';//库房id
  kqId: string = '';//库区id
  materialCode: string = '';//物资编码
  materialName: string = '';//物资名称
  accountName: string = ''//账户别名
  workOrder: string = ''//工作令
  dateRange = []//时间

  pageSize: number = 10
  pageIndex: number = 1//页码下标
  totalSize: number = 0//总条数
  isAllDisplayDataChecked = false;//是否是全选状态
  isIndeterminate = false;//是否是半选中状态
  listOfDisplayData = [];
  listData = []
  mapOfCheckedId: { [key: string]: boolean } = {};//选中的id
  numberOfChecked = 0;//选中的数量
  newIdList = []
  currentPageDataChange($event): void {
    this.listOfDisplayData = $event;
    this.refreshStatus();
  }
  refreshStatus(): void {
    this.isAllDisplayDataChecked = this.listOfDisplayData.every(item => this.mapOfCheckedId[item.id]);
    if (this.listData.length == 0) {
      this.isAllDisplayDataChecked = false
    }
    this.isIndeterminate = this.listOfDisplayData.some(item => this.mapOfCheckedId[item.id]) && !this.isAllDisplayDataChecked;
    this.numberOfChecked = this.listData.filter(item => this.mapOfCheckedId[item.id]).length;
    // 选中的id
    let checkedList = this.listData.filter(item => this.mapOfCheckedId[item.id])
    let newIds = []
    checkedList.forEach(item => {
      newIds.push(item.id)
    })
    this.newIdList = newIds
  }
  checkAll(value: boolean): void {
    this.listOfDisplayData.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }
  // 获取多发/多收记录列表
  getRecordList(type?) {
    if(type){
      this.pageIndex = 1
    }
    let _newData = {}
    let _data = {
      accountAlisa: this.accountName,
      commandContent: this.workOrder,
      materialCode: this.materialCode,
      materialName: this.materialName,
      warehouseId: this.kfId,
      warehouseAreaId: this.kqId,
      sort:'createDate,desc',
      page: this.pageIndex - 1,
      size: this.pageSize
    }
    if (this.dateRange.length != 0) {
      _newData = {
        ..._data,
        dateList:this.dateRange
      }
    } else {
      _newData = {
        ..._data
      }
    }
    this.ManysendreciveListService.getRecordList(_newData).subscribe(res => {
      this.listData = res.content
      this.totalSize = res.totalElements
    })
  }
  // 点击页码
  clickPage(index){
    this.pageIndex = index
    this.getRecordList()
  }

  // modal start
  // 获取账户别名列表
  getAccount(){
    this.ManysendreciveListService.getZHBM().subscribe(res=>{
      this.BMList = res
    })
  }
  isShowModal: boolean = false
  modalType: number = 1 //多发 或 多收
  handleCancel() {
    this.isShowModal = false
  }
  showModal(type) {
    this.isShowModal = true
    this.modalType = type
    // 清空值
    this.modalTableDetail = []
    this.BMIdModal = ''
    this.commandStrModal = ''
    this.reserveNumModal = ''
    this.selectedDetail = 0
    this.kfIdModal = ''
    this.kqIdModal = ''
    this.materialCodeModal = ''
    this.materialNameModal = ''
    this.dateRangeModal = []
    this.modalTable.forEach(item=>{  
      item.isEdit = false    
    })
    this.getInOutList()
    // 清空值
    if(type==1){
      this.subType = 'adjust_amount_more'
    }else if(type==2){
      this.subType = 'adjust_amount_less'
    }
  }
  kfIdModal: string = ''//模态框库房id
  kqIdModal: string = ''//模态框库区id
  materialCodeModal: string = ''//模态框物料编码
  materialNameModal: string = ''//模态框物料名称
  dateRangeModal = []//模态框日期
  accountNameModal: string = ''//模态框账户别名
  workOrderModal: string = ''//模态框工作令
  kqListModal = []//模态框库区列表
  BMList = []//选择别名
  BMIdModal:string = ''

  selectedkfModal(kfId) {
    this.kfIdModal = kfId
    this.kfList.forEach(item => {
      if (item.id == kfId) {
        this.kqListModal = item.warehouseAreas
      }
    })
    this.selectedDetail = 0
    this.modalTableDetail = []
    this.getInOutList('search')
  }
  selectedkqModal(kqId) {
    this.kqIdModal = kqId
    if (this.kfIdModal == '' && this.kqIdModal == '') {
      this.kfIdModal = ''
      this.kqIdModal = ''
    }
    this.getMaterialList('modalType')
    this.selectedDetail = 0
    this.modalTableDetail = []
    this.getInOutList('search')
  }
  selectedwlModal(wlCode) {
    this.materialCodeModal = wlCode
    this.wlList.forEach(item => {
      if (item.materialCode == wlCode) {
        this.materialNameModal = item.materialName
      }
    })
    if (wlCode == '') {
      this.materialNameModal = ''
    }
    this.selectedDetail = 0
    this.modalTableDetail = []
    this.getInOutList('search')
  }
  onDateChangeModal(result: Date): void {
    let startTime = this.formatDate(result[0])
    let endTime = this.formatDate(result[1])
    this.dateRangeModal = [startTime + " 00:00:00", endTime + " 23:59:59"]
    if(!startTime){
      this.dateRangeModal = []
    }
    this.selectedDetail = 0
    this.modalTableDetail = []
    this.getInOutList('search')
  }
  selectedBMModal(id){
    this.BMIdModal = id
  }

  subType:string = ''//提交的类型  多发/多收
  modalTable = []
  topIndex: number = 1
  topTotalSize: number = 0
  selectedDetail: number;//详情id
  // 获取出入库列表
  getInOutList(type?) {
    if(type){
      this.topIndex = 1
    }
    let _newData = {}
    let _data = {
      storehouseId: this.kfIdModal,
      storehouseAreaId: this.kqIdModal,
      materialCode: this.materialCodeModal,
      materialName: this.materialNameModal,
      sort:'createDate,desc',
      page: this.topIndex - 1,
      size: this.pageSize
    }
    if (this.dateRangeModal.length != 0) {
      _newData = {
        ..._data,
        dateList:this.dateRangeModal
      }
    }else{
      _newData = {
        ..._data
      }
    }
    this.ManysendreciveListService.getInOutList(_newData).subscribe(res => {
      res.content.forEach(item=>{
        item.isEdit = false
      })
      this.modalTable = res.content
      this.topTotalSize = res.totalElements
    })
  }
  clickPageModal(index){
    this.topIndex = index
    this.selectedDetail = 0
    this.modalTableDetail = []
    this.getInOutList()
  }
  showDetail(detailId) {
    this.modalTableDetail = []
    this.BMIdModal = ''
    this.commandStrModal = ''
    this.reserveNumModal = ''
    this.selectedDetail = detailId
    this.modalTable.forEach(item=>{
      if(item.id == detailId){
        item.isEdit = true
        this.modalTableDetail = [
          ...this.modalTableDetail,item
        ]
      }else{
        item.isEdit = false
      }
    })
  }

  modalTableDetail = []
  reserveNumModal:string = ''//调整数
  commandStrModal:string = ''//备注
  markList = []
  getGZLList(){
    this.ManysendreciveListService.getGZL().subscribe(res=>{
      this.markList = res.content
    })
  }
  selectedGZLModal(id){
    this.commandStrModal = id
  }
  // 新增 多发/多收
  addManyAdjust(){
    let _detail = this.modalTableDetail[0]
    if(_detail){
      let _dataJson = {
        dictType:this.subType,//类型（多发/多收）
        accountAliasId:this.BMIdModal,//事务处理（账户别名）
        commandId:this.commandStrModal,//备注（工作令）
        count:_detail.amount,//数量
        inoutId:_detail.id,//出入库记录表主键
        isAdjust:false,//是否调整
        reserveCount:this.reserveNumModal,//总调整数
        reserveNum:this.reserveNumModal//调整数
      }
      this.ManysendreciveListService.addMany(_dataJson).subscribe(res=>{
        this.isShowModal = false
        this.getRecordList()
      })
    }else{
      this.message.create("error","请选择一条出入库记录")
    }
  }
  // 修改
  editManyAdjust(){
    this.nzModal.confirm({
      nzTitle: '确认保存吗？',
      nzOkText: '确认',
      nzCancelText: '取消',
      nzOnOk: () => {
        let checkedList = this.listData.filter(item => this.mapOfCheckedId[item.id])[0]
        console.log(checkedList)
        let _dataJson = {
          dictType:checkedList.typeStr=='多收'?'adjust_amount_less':'adjust_amount_more',
          accountAliasId:checkedList.accountAliasId,
          commandId:checkedList.commandId,
          count:checkedList.count,
          inoutId:checkedList.inoutId,
          isAdjust:checkedList.isAdjust,
          reserveCount:checkedList.reserveCount,
          reserveNum:checkedList.reserveNum
        }
        this.ManysendreciveListService.editMany(_dataJson).subscribe(res=>{
          this.getRecordList()
        })
      }
    })
  }
  // 删除
  deleteMany(){
    this.nzModal.confirm({
      nzTitle: '确定删除这些数据吗？',
      nzContent: '',
      nzOkText: '确认',
      nzCancelText: '取消',
      nzOnOk: () => {
        let _data = this.newIdList
        console.log(_data)
        this.ManysendreciveListService.delMany(_data).subscribe(res => {
          this.newIdList = []
          this.mapOfCheckedId = {}
          this.getRecordList()
        })
      }
    })
  }
  // 触发ERP
  goERPAdjust(){
    this.nzModal.confirm({
      nzTitle: '确定要触发ERP吗？',
      nzContent: '',
      nzOkText: '确认',
      nzCancelText: '取消',
      nzOnOk: () => {
        let _data = this.newIdList
        this.ManysendreciveListService.goREP(_data).subscribe(res => {
          this.newIdList = []
          this.mapOfCheckedId = {}
          this.getRecordList()
        })
      }
    })
  }
}